# -*- coding: utf-8 -*-

from osv import fields,osv
from openerp.tools.translate import _
import datetime

CHARGE_TYPES = [
    ('normal','普通费用'),
    ('deposit','押金'),
    ('advances','预收款'),
    ('outbuildings','附属建筑费用')
]

class pm_charge_add(osv.osv_memory):
    _name = 'pm.charge.add'
    _columns = {
        'name':fields.char(string='缴费'),
        'charge_type':fields.selection(CHARGE_TYPES,string='收费类别'),
        'project_id':fields.many2one('pm.project',string='所属管理处'),
        'area_id':fields.many2one('pm.project.area',string='所属区域',domain="[('project_id','=',project_id)]"),
        'building_id':fields.many2one('pm.project.building',string='所属楼栋',help='Building',domain="[('project_area_id','=',area_id)]"),
        'room_id':fields.many2one('pm.project.building.room',string='所属房间',required=True,domain="[('building_id','=',building_id)]"),
        'partner_id':fields.many2one('res.partner',string='客户名称'),
        'receivable_amount':fields.float(string='应收金额'),
        'actual_receive_amount':fields.float(string='实收金额'),
        'late_payment_amount':fields.float(string='滞纳金'),
        'discount_amount':fields.float(string='优惠金额'),
        'last_left_amount':fields.float(string='上次余额'),
        'current_left_amount':fields.float(string='本次余额'),
        'receivable_amount_total':fields.float(string='应收合计'),
        'charge_amount':fields.float(string='交款金额'),
        'payment_method':fields.many2one('pm.parameter',string='付款方式',domain="[('category_code','=','JFFS')]"),
        #'cost_room_items':fields.many2many('pm.cost.item.room',string='收费项'),
        #'receivables':fields.many2many('pm.cost.receivable',string='应收项'),
        'receivables':fields.one2many('pm.charge.add.receivable','charge_add_id',string='应收项'),
        'remark':fields.char(string='收费备注',size=400),
    }

    def change_room_id(self,cr,uid,ids,room_id,context=None):
        values = {}

        receivable_amount = 0.0
        receivable_amount_total = 0.0
        last_left_amount = 0.0
        current_left_amount = 0.0

        last_charge_id = self.pool.get('pm.charge').search(cr,uid,[('room_id','=',room_id)],limit=1,order='input_time',context=context)
        if last_charge_id:
            last_item = self.pool.get('pm.charge').browse(cr,uid,last_charge_id[0],context=context)
            last_left_amount = last_item.current_left_amount

        re_ids = self.pool.get('pm.cost.receivable').search(cr,uid,[('room_id','=',room_id),('state','=','recorded')],context=context)
        if not re_ids:
            raise osv.except_osv(_('没有费用'),_('此房间暂时没有需要收费的项目')) 
        rows = []
        for item in self.pool.get('pm.cost.receivable').read(cr,uid,re_ids,context=context):
            item['receivable_id'] = item['id']
            item['room_id'] = room_id
            item['cost_item_id'] = item['cost_item_id'][0]
            item['partner_id'] = item['partner_id'][0]
            rows.append(item)
            receivable_amount += item['amount']
        
        decimal_part = receivable_amount - receivable_amount//1.0
        if decimal_part == 0.0:
            current_left_amount = last_left_amount
            receivable_amount_total = receivable_amount
        elif last_left_amount>=decimal_part:
            receivable_amount_total = receivable_amount//1.0 + 1
            current_left_amount = last_left_amount - decimal_part
        else:
            receivable_amount_total = receivable_amount//1.0 + 1
            current_left_amount = 1 - decimal_part - last_left_amount

        values['receivables'] = rows
        values['last_left_amount'] = last_left_amount 
        values['current_left_amount'] = current_left_amount
        values['receivable_amount'] = receivable_amount
        values['receivable_amount_total'] = receivable_amount_total
        values['actual_receive_amount'] = receivable_amount_total
        values['charge_amount'] = receivable_amount_total
        values['partner_id'] = rows and rows[0]['partner_id'] or 0
        return {'value':values}

    def change_receivables(self,cr,uid,ids,receivables,context=None):
        print 'change_receivables called'
        print 'receivables is %s ' % receivables
        items = self.read(cr,uid,ids,[],context=context)
        print 'items is %s ' % items
        return {'value':{}}

    def add_charge(self,cr,uid,ids,context=None):
        item = self.read(cr,uid,ids[0],[],context=context)
        print 'charge_add item is %s' % item
        item['input_man'] = uid
        item['name'] = 'SF20141006001'
        item['project_id'] = item['project_id'][0]
        item['area_id'] = item['area_id'][0]
        item['building_id'] = item['building_id'][0]
        item['room_id'] = item['room_id'][0]
        item['partner_id'] = item['partner_id'][0]
        item['payment_method'] = item['payment_method'] and item['payment_method'][0] or None 

        item['charge_type'] = 'normal'
        
        print 'item is %s' % item
        
        charge_id = self.pool.get('pm.charge').create(cr,uid,item,context=context)
        print 'create charge successful,charge_id is %s ' % charge_id
        charge_revs = self.pool.get('pm.charge.add.receivable').read(cr,uid,item['receivables'],['receivable_id'],context=context)
        cost_rev_ids = [item['receivable_id'][0] for item in charge_revs]
        print 'charge_revs is %s' % charge_revs 
        self.pool.get('pm.cost.receivable').write(cr,uid,cost_rev_ids,{'charge_id':charge_id,'state':'received'},context=context)

        return True

pm_charge_add()

class pm_charge_add_receivable(osv.osv_memory):
    _name = 'pm.charge.add.receivable'
    _columns = {
        'charge_add_id':fields.many2one('pm.charge.add',string='客户缴费'),
        'receivable_id':fields.many2one('pm.cost.receivable',string='应收项'),
        'room_id':fields.related('receivable_id','room_id',type='many2one',relation='pm.project.building.room',string='房间'),
        'cost_item_id':fields.related('receivable_id','cost_item_id',type='many2one',relation='pm.cost.item',string='收费项目'),
        'start_value':fields.related('receivable_id','start_value',type='float',string='起数'),
        'end_value':fields.related('receivable_id','end_value',type='float',string='止数'),
        'count':fields.related('receivable_id','count',type='float', string='数量'),
        'price':fields.related('receivable_id','price',type='float', string='单价'),
        'rate':fields.related( 'receivable_id','rate',type='float', string='倍率'),
        'amount':fields.related( 'receivable_id','amount',type='float',string='金额'),
        'billing_start_date':fields.related('receivable_id','billing_start_date',type='date', string='起始日期'),
        'billing_end_date':fields.related('receivable_id','billing_end_date',type='date',string='截止日期'),
        'checked':fields.boolean(string='选中'),
    }
pm_charge_add_receivable()
